import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class demo {
    public static void main(String[] args) throws SQLException {
        //1.0 创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/db01?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        //2.0 与数据库建立联系
        Connection connection = dataSource.getConnection();

        // 3.0 创建SQL语句
        String sql = "insert into student values('张三三',14)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        String sql1 = "select * from student";
        PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);

        //4.0 发送已经解析好的sql语句到数据库服务器中
        int n = preparedStatement.executeUpdate();
        System.out.println(n);

        //得到的是一个结果集
        ResultSet resultSet = preparedStatement1.executeQuery();
        while(resultSet.next()){
            String name = resultSet.getString("name");
            int age = resultSet.getInt("age");
            System.out.println(age + " " + name );
        }

        //5.0 释放资源
        preparedStatement.close();
        connection.close();

    }
}
